package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 下单，支付
 */
@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 去支付，生成订单
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        // 涉及表：orders order_detail
        // 获取用户id
        Long userId = BaseContext.getCurrentId();
        // 1、查询购物车数据：
        // select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);

        if(shoppingCartList == null || shoppingCartList.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }
        // 2、查询用户数据 select * from user where id = ?
        User user = userService.getById(userId);
        // 3、根据地址id查询地址数据
        // select * from address_book where id = ?
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }
        // 提前获取订单id
        long orderId = IdWorker.getId();
        //总价
        AtomicInteger amount = new AtomicInteger(0);
        // 4、保存订单明细数据：点了哪些菜品或套餐 来源于购物车数据
        /*for (ShoppingCart shoppingCart : shoppingCartList) {
            //拷贝： ShoppingCart shoppingCart --> OrderDetail orderDetail
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);

            // orderId单独设置
            orderDetail.setOrderId(orderId);
            // 订单总价 detailAmount 金额单独设置 数量 * 金额
            BigDecimal cartAmount = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(cartAmount.multiply(number));
            amount.add(orderDetail.getAmount());
        }*/

        //组装订单明细信息:点了哪些菜品或套餐 来源于购物车数据
        List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        // 5、保存订单数据，有许多数据需要单独设置
        //订单id
        orders.setId(orderId);
        //订单创建时间
        orders.setOrderTime(LocalDateTime.now());
        //订单结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);
        //总金额
        orders.setAmount(new BigDecimal(amount.get()));
        //用户id
        orders.setUserId(userId);
        //订单号
        orders.setNumber(String.valueOf(orderId));
        //用户名
        orders.setUserName(user.getName());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        //收货人联系电话
        orders.setPhone(addressBook.getPhone());
        //省+市+区域+详细地址
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        // 6、删除当前用户的购物车数据
        // delete from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(shoppingCartQueryWrapper);
    }
}
